import os
import platform
import subprocess
from typing import Dict, List


def is_valid_project_root(project_path: str) -> bool:
    """检查安卓项目根目录是否有效（是否存在gradle等关键文件）"""
    required_files = ["gradle.properties"]
    for file in required_files:
        if not os.path.exists(os.path.join(project_path, file)):
            return False
    return True


def run_packing_process(project_path: str, log_append) -> Dict:
    """执行安卓项目打包流程（调用gradlew构建）"""
    result = {"errors": [], "apk_files": []}
    gradlew = "gradlew.bat" if os.name == "nt" else "./gradlew"
    gradlew_path = os.path.join(project_path, gradlew)

    # 赋予执行权限（非Windows）
    if os.name != "nt":
        try:
            import stat
            st = os.stat(gradlew_path)
            os.chmod(gradlew_path, st.st_mode | stat.S_IEXEC)
        except Exception as e:
            result["errors"].append(f"设置gradlew权限失败：{str(e)}")
            return result

    # 清理项目
    clean_result = subprocess.run(
        [gradlew_path, "clean"],
        cwd=project_path,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    if clean_result.returncode != 0:
        result["errors"].append(f"清理失败：{clean_result.stderr}")
        return result
    log_append(clean_result.stdout)

    # 构建debug包
    build_result = subprocess.run(
        [gradlew_path, "assembleDebug"],
        cwd=project_path,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    if build_result.returncode != 0:
        result["errors"].append(f"构建失败：{build_result.stderr}")
        return result
    log_append(build_result.stdout)

    # 查找生成的APK
    apk_dir = os.path.join(project_path, "app/build/outputs/apk/debug")
    for root, _, files in os.walk(apk_dir):
        for file in files:
            if file.endswith(".apk"):
                result["apk_files"].append(os.path.join(root, file))
    return result


def install_apk(device_sn: str, apk_path: str) -> Dict[str, str]:
    try:
        command = ["adb", "-s", device_sn, "install", apk_path]
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="ignore",
            timeout=300,  # 5分钟超时
        )

        if result.returncode == 0:
            output = result.stdout or "安装成功"
            success = True
        else:
            output = f"安装失败:\n{result.stderr or result.stdout}"
            success = False

    except subprocess.TimeoutExpired:
        output = "安装超时 (5分钟)"
        success = False
    except Exception as e:
        output = f"执行安装命令时发生错误: {str(e)}"
        success = False

    return {"success": success, "output": output}